# -*- coding: utf-8 -*-
"""Setup the pythonblog application"""
import logging

from pythonblog.config.environment import load_environment
from pythonblog.model import meta
from pythonblog import model
from authkit.users.sqlalchemy_driver import UsersFromDatabase
from pythonblog.model.account import *
from pythonblog.model.navigation import *
from pythonblog.model.content import * 

log = logging.getLogger(__name__)

import md5 as _md5
def md5(password, secret='pythonblog'):
    """
    secret value should be the same as the one configured for
    authkit.form.authenticate.user.encrypt.secret in development.ini file
    """
    result = _md5.md5(password)
    result.update(secret)
    result = result.hexdigest()
    return result

def setup_app(command, conf, vars):
    """Place any commands to setup pythonblog here"""
    load_environment(conf.global_conf, conf.local_conf)

    log.info("Adding the AuthKit model...")
    users = UsersFromDatabase(model)
    # Create the tables if they don't already exist
    meta.metadata.create_all(bind=meta.engine)
    
    log.info("Adding roles and uses...")
    userName1 = "user1"
    userName2 = "user2"
    users.role_create("user")
    users.role_create("admin")
    users.user_create(userName1, password=md5(userName1))
    users.user_create(userName2, password=md5(userName2))
    users.user_add_role(userName1, role="user")
    users.user_add_role(userName2, role="admin")
    meta.Session.flush()
    
    log.info("Adding user profiles...")
    user1 = UserProfile()
    user1.userName = userName1
    user1.realName =  u'小刘'    
    user1.email = 'user1@gmail.com'
    meta.Session.add(user1)
    
    user2 = UserProfile()
    user2.userName = userName2
    user2.realName =  u'小冯'
    user2.email = 'user2@gmail.com'
    user2.gender = 1
    user2.city = u'上海'
    meta.Session.add(user2)
    meta.Session.flush()
    
    log.info("Adding sections...")    
    section = Section()
    section.id = 1
    section.name = u'职场麻辣烫'
    section.path = 'career'
    section.message = u'欢迎来到职场麻辣烫！'
    meta.Session.add(section)
    
    section = Section()
    section.id = 2
    section.name = u'毕业生家园'
    section.path = 'graduation'
    section.message = u'欢迎来到毕业生家园！'
    meta.Session.add(section)
    
    section = Section()
    section.id = 3
    section.name = u'职商提升'
    section.path = 'promotion'
    section.message = u'欢迎来到职商老大哥！'
    meta.Session.add(section)
    
    section = Section()
    section.id = 4
    section.name = u'待业VS创业'
    section.path = 'newcareer'
    section.message = u'欢迎来到待业VS创业！'
    meta.Session.add(section)
    
    section = Section()
    section.id = 5
    section.name = u'八卦休闲'
    section.path = 'fun'
    section.message = u'欢迎来到八卦休闲！'
    meta.Session.add(section)    
    meta.Session.flush()    
    
    meta.Session.commit()
    log.info("Successfully set up.")
